<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">






  
  
  <link rel="stylesheet" media="all" href="/lib/Han/dist/han.min.css?v=3.3">




<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/favicon.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon.png?v=5.1.4">


  <link rel="mask-icon" href="/images/favicon.png?v=5.1.4" color="#222">





  <meta name="keywords" content="C++," />





  <link rel="alternate" href="/atom.xml" title="平步青云win" type="application/atom+xml" />






<meta name="description" content="泛型编程，深入探索面向对象之继承关系所形成的对象模型，包含this指针，虚指针，虚表，虚极至以及虚函数造成的多样效果">
<meta name="keywords" content="C++">
<meta property="og:type" content="article">
<meta property="og:title" content="C++对象模型">
<meta property="og:url" content="https://zxpgo.github.io/2019/08/06/C++对象模型/index.html">
<meta property="og:site_name" content="平步青云win">
<meta property="og:description" content="泛型编程，深入探索面向对象之继承关系所形成的对象模型，包含this指针，虚指针，虚表，虚极至以及虚函数造成的多样效果">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://raw.githubusercontent.com/zxpgo/images/master/img/20190830161353.png">
<meta property="og:image" content="https://raw.githubusercontent.com/zxpgo/images/master/img/20190901203455.png">
<meta property="og:updated_time" content="2020-04-25T09:35:03.335Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="C++对象模型">
<meta name="twitter:description" content="泛型编程，深入探索面向对象之继承关系所形成的对象模型，包含this指针，虚指针，虚表，虚极至以及虚函数造成的多样效果">
<meta name="twitter:image" content="https://raw.githubusercontent.com/zxpgo/images/master/img/20190830161353.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"right","display":"post","offset":10,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: 'PAO8LM7QB1',
      apiKey: '',
      indexName: 'Blog',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://zxpgo.github.io/2019/08/06/C++对象模型/"/>





  <title>C++对象模型 | 平步青云win</title>
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?7a4517a3ce6d7c50203655d056f01ac3";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-right page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">平步青云win</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description"></h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-随笔">
          <a href="/sui" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            随笔
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
			
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://zxpgo.github.io/2019/08/06/C++对象模型/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="zxp">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="平步青云win">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">C++对象模型</h2>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-08-06T11:44:14+08:00">
                2019-08-06
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/C/" itemprop="url" rel="index">
                    <span itemprop="name">C++</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/2019/08/06/C++对象模型/" class="leancloud_visitors" data-flag-title="C++对象模型">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body han-init-context" itemprop="articleBody">

      
      

      
        <p>泛型编程，深入探索面向对象之继承关系所形成的对象模型，包含this指针，虚指针，虚表，虚极至以及虚函数造成的多样效果<a id="more"></a></p>
<h1 id="类型转换"><a href="#类型转换" class="headerlink" title="类型转换"></a>类型转换</h1><h2 id="转换函数"><a href="#转换函数" class="headerlink" title="转换函数"></a>转换函数</h2><p>转换函数没有返回类型；转换函数声明为const。</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Fraction</span> &#123;</span></span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">	Fraction(<span class="keyword">int</span> num, <span class="keyword">int</span> den = <span class="number">1</span>) </span><br><span class="line">		: m_numerator(num), m_denominator(den)&#123;&#125;</span><br><span class="line">	<span class="function"><span class="keyword">operator</span> <span class="title">double</span><span class="params">()</span> <span class="keyword">const</span> </span>&#123;  <span class="comment">//转换函数</span></span><br><span class="line">		<span class="keyword">return</span> (<span class="keyword">double</span>)m_numerator / m_denominator;</span><br><span class="line">	&#125;</span><br><span class="line"><span class="keyword">private</span>:</span><br><span class="line">	<span class="keyword">int</span> m_numerator;</span><br><span class="line">	<span class="keyword">int</span> m_denominator;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="function">Fraction <span class="title">f</span><span class="params">(<span class="number">3</span>, <span class="number">5</span>)</span></span>;</span><br><span class="line"><span class="keyword">double</span>  d = <span class="number">4</span> + f; <span class="comment">//调用operator double()将f转为0.6</span></span><br></pre></td></tr></table></figure>
<p>对于4+f，首先去是否存在全局函数，operator+，第一个参数为int，第二个参数为Fraction。如果没有就去调用转换函数operator double()。</p>
<p>如果Fraction类如下，则不会调用转换函数operator double()，而是调用<code>operator+(const int i, const Fraction &amp; frac)</code>函数。</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Fraction</span> &#123;</span></span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">	Fraction(<span class="keyword">int</span> num, <span class="keyword">int</span> den = <span class="number">1</span>)</span><br><span class="line">		: m_numerator(num), m_denominator(den) &#123;&#125;</span><br><span class="line">	<span class="function"><span class="keyword">operator</span> <span class="title">double</span><span class="params">()</span> <span class="keyword">const</span> </span>&#123;  <span class="comment">//转换函数</span></span><br><span class="line">		<span class="keyword">return</span> (<span class="keyword">double</span>)m_numerator / m_denominator;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">friend</span> <span class="keyword">double</span> <span class="keyword">operator</span>+(<span class="keyword">const</span> <span class="keyword">int</span> i, <span class="keyword">const</span> Fraction &amp; frac);</span><br><span class="line"><span class="keyword">private</span>:</span><br><span class="line">	<span class="keyword">int</span> m_numerator;</span><br><span class="line">	<span class="keyword">int</span> m_denominator;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">double</span> <span class="keyword">operator</span>+(<span class="keyword">const</span> <span class="keyword">int</span> i, <span class="keyword">const</span> Fraction &amp; frac) &#123;</span><br><span class="line">	<span class="keyword">return</span> i + (<span class="keyword">double</span>)frac.m_numerator / frac.m_denominator;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="non-explicit-one-argument-ctor"><a href="#non-explicit-one-argument-ctor" class="headerlink" title="non-explicit-one-argument ctor"></a>non-explicit-one-argument ctor</h2><p>允许一个实参的非explicit构造函数。将其他类型转换成类的类型。</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Fraction</span> &#123;</span></span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">	Fraction(<span class="keyword">int</span> num, <span class="keyword">int</span> den = <span class="number">1</span>)</span><br><span class="line">		: m_numerator(num), m_denominator(den) &#123;&#125;</span><br><span class="line"><span class="comment">//	operator double() const &#123;  //转换函数</span></span><br><span class="line"><span class="comment">//		return (double)m_numerator / m_denominator;</span></span><br><span class="line"><span class="comment">//	&#125; //该函数存在时，会存在二义性</span></span><br><span class="line">	Fraction <span class="keyword">operator</span>+(<span class="keyword">const</span> Fraction&amp; f) &#123;</span><br><span class="line">		<span class="keyword">return</span> Fraction(<span class="keyword">this</span>-&gt;m_numerator * f.m_denominator + f.m_numerator * <span class="keyword">this</span>-&gt;m_denominator, </span><br><span class="line">			<span class="keyword">this</span>-&gt;m_denominator * f.m_denominator);</span><br><span class="line">	&#125;</span><br><span class="line"><span class="keyword">private</span>:</span><br><span class="line">	<span class="keyword">int</span> m_numerator;</span><br><span class="line">	<span class="keyword">int</span> m_denominator;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	<span class="function">Fraction <span class="title">f</span><span class="params">(<span class="number">3</span>, <span class="number">5</span>)</span></span>;</span><br><span class="line">	Fraction  d =  f + <span class="number">4</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>会将4转成为Fraction类型，因为会调用构造函数进行转换。</p>
<p>如果operator double() 存在时，会存在二义性，因为4可以转成Fraction，f可以转成double。</p>
<h2 id="explicit-one-argument-ctor"><a href="#explicit-one-argument-ctor" class="headerlink" title="explicit-one-argument ctor"></a>explicit-one-argument ctor</h2><figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Fraction</span> &#123;</span></span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">	<span class="function"><span class="keyword">explicit</span> <span class="title">Fraction</span><span class="params">(<span class="keyword">int</span> num, <span class="keyword">int</span> den = <span class="number">1</span>)</span></span></span><br><span class="line">		: m_numerator(num), m_denominator(den) &#123;&#125;</span><br><span class="line">	<span class="function"><span class="keyword">operator</span> <span class="title">double</span><span class="params">()</span> <span class="keyword">const</span> </span>&#123;  <span class="comment">//转换函数</span></span><br><span class="line">		<span class="keyword">return</span> (<span class="keyword">double</span>)m_numerator / m_denominator;</span><br><span class="line">	&#125; </span><br><span class="line">	Fraction <span class="keyword">operator</span>+(<span class="keyword">const</span> Fraction&amp; f) &#123;</span><br><span class="line">		<span class="keyword">return</span> Fraction(<span class="keyword">this</span>-&gt;m_numerator * f.m_denominator + f.m_numerator * <span class="keyword">this</span>-&gt;m_denominator, </span><br><span class="line">			<span class="keyword">this</span>-&gt;m_denominator * f.m_denominator);</span><br><span class="line">	&#125;</span><br><span class="line"><span class="keyword">private</span>:</span><br><span class="line">	<span class="keyword">int</span> m_numerator;</span><br><span class="line">	<span class="keyword">int</span> m_denominator;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	<span class="function">Fraction <span class="title">f</span><span class="params">(<span class="number">3</span>, <span class="number">5</span>)</span></span>;</span><br><span class="line">	Fraction  d =  f + <span class="number">4</span>; <span class="comment">//不会将4转成Fraction，所以会报错</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>标准库中的转换函数：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">template</span>&lt;<span class="class"><span class="keyword">class</span> <span class="title">Alloc</span>&gt;</span></span><br><span class="line"><span class="class"><span class="title">class</span> <span class="title">vector</span>&lt;bool, Alloc&gt;</span></span><br><span class="line"><span class="class">&#123;</span></span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">	<span class="keyword">typedef</span> __bit_reference reference;</span><br><span class="line"><span class="keyword">protected</span>:</span><br><span class="line">	reference <span class="keyword">operator</span>[](size_type n)&#123;</span><br><span class="line">		<span class="keyword">return</span> *(begin() + difference_type(n));</span><br><span class="line">	&#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">struct</span> __<span class="title">bit_reference</span>&#123;</span></span><br><span class="line">    <span class="keyword">unsigned</span> <span class="keyword">int</span> * p;</span><br><span class="line">    <span class="keyword">unsigned</span> <span class="keyword">int</span> mask;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">    <span class="function"><span class="keyword">operator</span> <span class="title">bool</span><span class="params">()</span> <span class="keyword">const</span> </span>&#123; <span class="keyword">return</span> !(!(*p &amp; mask)); &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<h1 id="pointer-liker-classes"><a href="#pointer-liker-classes" class="headerlink" title="pointer-liker classes"></a>pointer-liker classes</h1><h2 id="智能指针"><a href="#智能指针" class="headerlink" title="智能指针"></a>智能指针</h2><figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">template</span>&lt;<span class="class"><span class="keyword">class</span> <span class="title">T</span>&gt;</span></span><br><span class="line"><span class="class"><span class="title">class</span> <span class="title">shared_ptr</span> &#123;</span></span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">	T &amp; <span class="keyword">operator</span>*() <span class="keyword">const</span> &#123;</span><br><span class="line">		<span class="keyword">return</span> *px;</span><br><span class="line">	&#125;</span><br><span class="line">	T * <span class="keyword">operator</span>-&gt;() <span class="keyword">const</span> &#123;</span><br><span class="line">		<span class="keyword">return</span> px;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="built_in">shared_ptr</span>(T * p) : px(p) &#123;&#125;</span><br><span class="line"><span class="keyword">private</span>:</span><br><span class="line">	T * px;</span><br><span class="line">	<span class="keyword">long</span> * pn; </span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">Foo</span> &#123;</span></span><br><span class="line"><span class="comment">//...</span></span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">	<span class="function"><span class="keyword">void</span> <span class="title">method</span><span class="params">(<span class="keyword">void</span>)</span></span>&#123;<span class="comment">//..&#125;</span></span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="built_in">shared_ptr</span>&lt;Foo&gt; sp(<span class="keyword">new</span> Foo);</span><br><span class="line"><span class="function">Foo <span class="title">f</span><span class="params">(*sp)</span></span>;</span><br><span class="line">sp-&gt;method(); <span class="comment">//等价于px-&gt;method();</span></span><br></pre></td></tr></table></figure>
<h2 id="迭代器"><a href="#迭代器" class="headerlink" title="迭代器"></a>迭代器</h2><figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">template</span> &lt;<span class="class"><span class="keyword">class</span> <span class="title">T</span>, <span class="title">class</span> <span class="title">Ref</span>, <span class="title">class</span> <span class="title">Ptr</span>&gt;</span></span><br><span class="line"><span class="class"><span class="title">struct</span> __<span class="title">list_iterator</span> &#123;</span></span><br><span class="line">	<span class="keyword">typedef</span> __list_node&lt;T&gt;* link_type;</span><br><span class="line">	link_type node;</span><br><span class="line">	reference <span class="keyword">operator</span>*() <span class="keyword">const</span> &#123; <span class="keyword">return</span> (*node).data; &#125;</span><br><span class="line">	pointer <span class="keyword">operator</span>-&gt;() <span class="keyword">const</span> &#123; <span class="keyword">return</span> &amp;(<span class="keyword">operator</span>*());  &#125;</span><br><span class="line">	self&amp; <span class="keyword">operator</span>++() &#123;&#125;</span><br><span class="line">	self&amp; <span class="keyword">operator</span>--() &#123;&#125;</span><br><span class="line">	self&amp; <span class="keyword">operator</span>++(<span class="keyword">int</span>) &#123;&#125;</span><br><span class="line">	self&amp; <span class="keyword">operator</span>--(<span class="keyword">int</span>) &#123;<span class="comment">//...</span></span><br><span class="line">	&#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="built_in">list</span>&lt;Foo&gt;::iterator ite;</span><br><span class="line">*ite;</span><br><span class="line">ite-&gt;method(); <span class="comment">//相等于(&amp;(*ite))-&gt;method();</span></span><br></pre></td></tr></table></figure>
<h1 id="function-like-classes仿函数"><a href="#function-like-classes仿函数" class="headerlink" title="function-like classes仿函数"></a>function-like classes仿函数</h1><p>类中重载operator ()函数。</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">template</span>&lt;<span class="class"><span class="keyword">class</span> <span class="title">T</span>&gt;</span></span><br><span class="line"><span class="class"><span class="title">struct</span> <span class="title">identity</span>&#123;</span></span><br><span class="line">	<span class="keyword">const</span> T &amp;;</span><br><span class="line">	<span class="keyword">operator</span>()(<span class="keyword">const</span> T &amp; x) cosnt &#123; <span class="keyword">return</span> x &#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">template</span> &lt;<span class="class"><span class="keyword">class</span> <span class="title">Pair</span>&gt;</span></span><br><span class="line"><span class="class"><span class="title">struct</span> <span class="title">select1st</span>&#123;</span></span><br><span class="line">	<span class="keyword">const</span> <span class="keyword">typename</span> Pair::first_type &amp; </span><br><span class="line">	<span class="keyword">operator</span>()(<span class="keyword">const</span> Pair&amp; x) <span class="keyword">const</span> &#123;</span><br><span class="line">		<span class="keyword">return</span> x.first;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">template</span>&lt;<span class="class"><span class="keyword">class</span> <span class="title">Pair</span>&gt;</span></span><br><span class="line"><span class="class"><span class="title">struct</span> <span class="title">select2en</span> &#123;</span></span><br><span class="line">	<span class="keyword">const</span> <span class="keyword">typename</span> Pair::second_type &amp;</span><br><span class="line">		<span class="keyword">operator</span>()(<span class="keyword">const</span> Pair&amp; x) <span class="keyword">const</span> &#123;</span><br><span class="line">		<span class="keyword">return</span> x.second;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;;</span><br><span class="line"><span class="keyword">template</span> &lt;<span class="class"><span class="keyword">class</span> <span class="title">T1</span>, <span class="title">class</span> <span class="title">T2</span>&gt;</span></span><br><span class="line"><span class="class"><span class="title">struct</span> <span class="title">pair</span> &#123;</span></span><br><span class="line">	T1 first;</span><br><span class="line">	T2 second;</span><br><span class="line">	pair() : first(T1()), second(T2()) &#123;&#125;</span><br><span class="line">	pair(<span class="keyword">const</span> T1 &amp; a, <span class="keyword">const</span> T2 &amp; b) :first(a), second(b) &#123;&#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<h1 id="模板"><a href="#模板" class="headerlink" title="模板"></a>模板</h1><h2 id="类模板"><a href="#类模板" class="headerlink" title="类模板"></a>类模板</h2><figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt;</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">complex</span>&#123;</span></span><br><span class="line"><span class="keyword">private</span>:</span><br><span class="line">    T re, im;</span><br><span class="line"><span class="keyword">public</span>: </span><br><span class="line">    <span class="keyword">complex</span>(T r = <span class="number">0</span>, T i = <span class="number">0</span>) : re(i), im(i)&#123;&#125;</span><br><span class="line">&#125;;</span><br><span class="line"><span class="keyword">complex</span>&lt;<span class="keyword">double</span>&gt; c1(<span class="number">1.2</span>, <span class="number">1.5</span>);</span><br></pre></td></tr></table></figure>
<h2 id="函数模板"><a href="#函数模板" class="headerlink" title="函数模板"></a>函数模板</h2><figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">template</span>&lt;<span class="class"><span class="keyword">class</span> <span class="title">T</span>&gt;</span></span><br><span class="line"><span class="class"><span class="title">inline</span> <span class="title">const</span> <span class="title">T</span>&amp; <span class="title">min</span>(<span class="title">const</span> <span class="title">T</span>&amp; <span class="title">a</span>, <span class="title">const</span> <span class="title">T</span>&amp; <span class="title">b</span>)&#123;</span></span><br><span class="line">    <span class="keyword">return</span> b &lt; a ? b : a;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>编译器会对函数模板进行参数推导。</p>
<h2 id="成员模板"><a href="#成员模板" class="headerlink" title="成员模板"></a>成员模板</h2><figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">template</span> &lt;<span class="class"><span class="keyword">class</span> <span class="title">T1</span>, <span class="title">class</span> <span class="title">T2</span>&gt;</span></span><br><span class="line"><span class="class"><span class="title">struct</span> <span class="title">pair</span>&#123;</span></span><br><span class="line">	<span class="keyword">typedef</span> T1 first_type;</span><br><span class="line">	<span class="keyword">typedef</span> T2 second_type;</span><br><span class="line">	</span><br><span class="line">	T1 first;</span><br><span class="line">	T2 second;</span><br><span class="line">	</span><br><span class="line">	pair() : first(T1()), second(T2())&#123;&#125;</span><br><span class="line">	pair(<span class="keyword">const</span> T1&amp; a, <span class="keyword">const</span> T2&amp; b) : first(a), second(b)P&#123;&#125;</span><br><span class="line">	</span><br><span class="line">	<span class="keyword">template</span>&lt;<span class="class"><span class="keyword">class</span> <span class="title">U1</span>, <span class="title">class</span> <span class="title">U2</span>&gt;</span></span><br><span class="line"><span class="class">	<span class="title">pair</span>(<span class="title">const</span> <span class="title">pair</span>&lt;U1, U2&gt;&amp; <span class="title">p</span>) :</span> first(p.first), second(p.second)&#123;&#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Base1</span>&#123;</span>&#125;;</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Derived1</span> :</span> <span class="keyword">public</span> Base1&#123;&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Base2</span>&#123;</span>&#125;;</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Derived2</span> :</span> <span class="keyword">public</span> Base2&#123;&#125;</span><br><span class="line"></span><br><span class="line">pair&lt;Derived1, Derived2&gt; p;</span><br><span class="line">pair&lt;Base1, Base2&gt; p2(p);</span><br></pre></td></tr></table></figure>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">template</span>&lt;<span class="keyword">typename</span> _Tp&gt;</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">shared_ptr</span>:</span> <span class="keyword">public</span> __shared_ptr&lt;_Tp&gt;&#123;</span><br><span class="line">	<span class="keyword">template</span>&lt;<span class="keyword">typename</span> _Tp1&gt;</span><br><span class="line">	<span class="function"><span class="keyword">explicit</span> <span class="title">shared_ptr</span><span class="params">(_Tp1 * __p)</span> </span></span><br><span class="line">	: __shared_ptr&lt;_Tp&gt;(__p)&#123;&#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line">Base1 * ptr = <span class="keyword">new</span> Derived1;</span><br><span class="line"><span class="built_in">shared_ptr</span>&lt;Base1&gt; sptr(<span class="keyword">new</span> Derived1);</span><br></pre></td></tr></table></figure>
<h2 id="模板特化"><a href="#模板特化" class="headerlink" title="模板特化"></a>模板特化</h2><figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">template</span>&lt;<span class="class"><span class="keyword">class</span> <span class="title">key</span>&gt;</span></span><br><span class="line"><span class="class"><span class="title">struct</span> <span class="title">hash</span>&#123;</span>&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">template</span>&lt;&gt;</span><br><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">hash</span>&lt;char&gt;&#123;</span></span><br><span class="line">	<span class="keyword">size_t</span> <span class="keyword">operator</span>()(<span class="keyword">char</span> x) <span class="keyword">const</span> &#123; <span class="keyword">return</span> x; &#125;</span><br><span class="line">&#125;;</span><br><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">hash</span>&lt;int&gt;&#123;</span></span><br><span class="line">	<span class="keyword">size_t</span> <span class="keyword">operator</span>()(<span class="keyword">int</span> x) <span class="keyword">const</span> &#123; <span class="keyword">return</span> x;&#125;  </span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<h2 id="模板偏特化"><a href="#模板偏特化" class="headerlink" title="模板偏特化"></a>模板偏特化</h2><figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//个数上的偏特化</span></span><br><span class="line"><span class="keyword">template</span>&lt;<span class="keyword">typename</span> T, <span class="keyword">typename</span> Alloc&gt;</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">vector</span>&#123;</span></span><br><span class="line"><span class="comment">//...</span></span><br><span class="line">&#125;;</span><br><span class="line"><span class="keyword">template</span>&lt;<span class="keyword">typename</span> Alloc=...&gt;</span><br><span class="line">class <span class="built_in">vector</span>&lt;<span class="keyword">bool</span>, Alloc&gt;&#123;<span class="comment">//偏特化，针对bool类型有专门的设计</span></span><br><span class="line"></span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">//范围上的偏特化</span></span><br><span class="line"><span class="keyword">template</span>&lt;<span class="keyword">typename</span> T&gt;</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">T</span>&#123;</span>&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">template</span>&lt;<span class="keyword">typename</span> U&gt;</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">C</span>&lt;U*&gt;&#123;</span>&#125;;</span><br><span class="line"></span><br><span class="line">C&lt;<span class="built_in">string</span>&gt; obj1;</span><br><span class="line">C&lt;<span class="built_in">string</span>*&gt; obj2;</span><br></pre></td></tr></table></figure>
<h2 id="模板模板参数"><a href="#模板模板参数" class="headerlink" title="模板模板参数"></a>模板模板参数</h2><figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">template</span>&lt;<span class="keyword">typename</span> T, <span class="keyword">template</span>&lt;<span class="keyword">typename</span> T&gt; <span class="class"><span class="keyword">class</span> <span class="title">Container</span>&gt;</span></span><br><span class="line"><span class="class"><span class="title">class</span> <span class="title">XCls</span>&#123;</span></span><br><span class="line"><span class="keyword">private</span>:</span><br><span class="line">	Container&lt;T&gt; c;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">	<span class="comment">//...</span></span><br><span class="line">&#125;;</span><br><span class="line"><span class="keyword">template</span>&lt;<span class="keyword">typename</span> T&gt;</span><br><span class="line"><span class="keyword">using</span> Lst = <span class="built_in">list</span>&lt;T, allocator&lt;T&gt;&gt;;</span><br><span class="line"></span><br><span class="line">XCls&lt;<span class="built_in">string</span>, <span class="built_in">list</span>&gt; mylst1; <span class="comment">//错误,因为需要设置第二参数，所以必须向下面那样使用</span></span><br><span class="line">XCls&lt;<span class="built_in">string</span>, Lst&gt; mylst2;</span><br></pre></td></tr></table></figure>
<p>下面情况不是模板模板参数：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">template</span>&lt;<span class="class"><span class="keyword">class</span> <span class="title">T</span>, <span class="title">class</span> <span class="title">Sequence</span> = <span class="title">deque</span>&lt;T&gt;&gt;</span></span><br><span class="line"><span class="class"><span class="title">class</span> <span class="title">stack</span>&#123;</span></span><br><span class="line"><span class="keyword">protected</span>:</span><br><span class="line">	Sequence c;</span><br><span class="line">	<span class="comment">//...</span></span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="built_in">stack</span>&lt;<span class="keyword">int</span>&gt; s1;</span><br><span class="line"><span class="built_in">stack</span>&lt;<span class="keyword">int</span>, <span class="built_in">list</span>&lt;<span class="keyword">int</span>&gt;&gt; s2;</span><br></pre></td></tr></table></figure>
<h2 id="模板参数可变"><a href="#模板参数可变" class="headerlink" title="模板参数可变"></a>模板参数可变</h2><figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">print</span><span class="params">()</span></span>&#123;&#125;</span><br><span class="line"><span class="keyword">template</span>&lt;<span class="keyword">typename</span> T, <span class="keyword">typename</span>... Types&gt;</span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">print</span><span class="params">(<span class="keyword">const</span> T&amp; firstArg, <span class="keyword">const</span> Types&amp;.. args)</span></span>&#123;</span><br><span class="line">	<span class="built_in">cout</span> &lt;&lt; firstArg &lt;&lt; <span class="built_in">endl</span>;</span><br><span class="line">	<span class="built_in">cout</span> &lt;&lt; <span class="keyword">sizeof</span>...(args) &lt;&lt; <span class="built_in">endl</span>;</span><br><span class="line">	print(args...);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h1 id="引用"><a href="#引用" class="headerlink" title="引用"></a>引用</h1><ul>
<li>引用必须有初值；</li>
<li>而且设置完初值，不能改变；（指针可以改变指向其他值）</li>
</ul>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">int</span> x = <span class="number">0</span>;</span><br><span class="line"><span class="keyword">int</span>&amp; r = x;</span><br><span class="line"><span class="keyword">int</span> x2 = <span class="number">5</span>;</span><br><span class="line">r = x2; <span class="comment">//r,x都是5</span></span><br></pre></td></tr></table></figure>
<p>注意：</p>
<p>引用的底部就是指针，所以实际上是4个字节。但是编译器会制造假象：大小相同，地址也相同。</p>
<p><code>sizeof(r) == sizeof(x), &amp;r = &amp;x</code>。</p>
<p><strong>Java里面的所有变量都是引用。</strong></p>
<p>引用通常不用于声明变量，而用于参数类型和返回类型的描述。</p>
<p>下面二者不能并存：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">double</span> <span class="title">imag</span><span class="params">(<span class="keyword">const</span> <span class="keyword">double</span>&amp; im)</span></span>&#123;&#125;</span><br><span class="line"><span class="function"><span class="keyword">double</span> <span class="title">imag</span><span class="params">(<span class="keyword">const</span> <span class="keyword">double</span> im)</span></span>&#123;&#125; <span class="comment">//存在二义性</span></span><br></pre></td></tr></table></figure>
<p>这是因为两个函数的签名相同。</p>
<h1 id="对象模型"><a href="#对象模型" class="headerlink" title="对象模型"></a>对象模型</h1><p>继承下，构造函数由内而外，析构函数由外而内。</p>
<p>组合下，构造函数由内而外，析构函数由外而内。</p>
<p>继承和组合下，构造函数由父类构造函数-&gt;组合对象的构造函数-&gt;子类本身的构造函数（VS2017中，可能不同编译器不同）。析构函数刚好相反。</p>
<h2 id="虚指针和虚表"><a href="#虚指针和虚表" class="headerlink" title="虚指针和虚表"></a>虚指针和虚表</h2><figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">A</span> &#123;</span></span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">	<span class="function"><span class="keyword">virtual</span> <span class="keyword">void</span> <span class="title">vfunc1</span><span class="params">()</span></span>;</span><br><span class="line">	<span class="function"><span class="keyword">virtual</span> <span class="keyword">void</span> <span class="title">vfunc2</span><span class="params">()</span></span>;</span><br><span class="line">	<span class="function"><span class="keyword">void</span> <span class="title">func1</span><span class="params">()</span></span>;</span><br><span class="line">	<span class="function"><span class="keyword">void</span> <span class="title">func2</span><span class="params">()</span></span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">private</span>:</span><br><span class="line">	<span class="keyword">int</span> m_data1, m_data2;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">B</span> :</span> <span class="keyword">public</span> A &#123;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">	<span class="function"><span class="keyword">virtual</span> <span class="keyword">void</span> <span class="title">vfunc1</span><span class="params">()</span></span>;</span><br><span class="line">	<span class="function"><span class="keyword">void</span> <span class="title">func2</span><span class="params">()</span></span>;</span><br><span class="line"><span class="keyword">private</span>:</span><br><span class="line">	m_data3;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">C</span> :</span> <span class="keyword">public</span> B &#123;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">	<span class="function"><span class="keyword">virtual</span> <span class="keyword">void</span> <span class="title">vfunc1</span><span class="params">()</span></span>;</span><br><span class="line">	<span class="function"><span class="keyword">void</span> <span class="title">func2</span><span class="params">()</span></span>;</span><br><span class="line"><span class="keyword">private</span>:</span><br><span class="line">	<span class="keyword">int</span> m_data1,m_data4;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<p><img src="https://raw.githubusercontent.com/zxpgo/images/master/img/20190830161353.png" alt=""></p>
<p>虚指针指向虚函数表。</p>
<p>如果虚函数没有重载，在虚表中的记录将会相同。</p>
<h1 id="this"><a href="#this" class="headerlink" title="this"></a>this</h1><figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">CDocument</span>&#123;</span></span><br><span class="line">	<span class="function"><span class="keyword">void</span> <span class="title">onFileOpen</span><span class="params">()</span></span>;</span><br><span class="line">    <span class="function"><span class="keyword">virtual</span> <span class="keyword">void</span> <span class="title">Serialize</span><span class="params">()</span></span>;</span><br><span class="line">    ...</span><br><span class="line">&#125;;</span><br><span class="line">CDocument::OnFileOpen()&#123;</span><br><span class="line">    ...</span><br><span class="line">    Serialize();</span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">virtual</span> <span class="title">Serialize</span><span class="params">()</span></span>;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">CMyDoc</span> :</span> <span class="keyword">public</span> CDocument&#123;</span><br><span class="line">    <span class="function"><span class="keyword">virtual</span> <span class="title">Serialize</span><span class="params">()</span></span>&#123;...&#125;</span><br><span class="line">&#125;;</span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span></span>&#123;</span><br><span class="line">    CMyDoc myDoc;</span><br><span class="line">    myDoc.onFileOpen();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h1 id="const"><a href="#const" class="headerlink" title="const"></a>const</h1><p>当成员函数的const和non-const版本同时存在，const object只会(只能)调用const版本，non-const object只会(只能)调用non-const。</p>
<hr>
<table>
<thead>
<tr>
<th style="text-align:center"></th>
<th style="text-align:center">const object（data members 不得变动）</th>
<th>non-const object(data members 可变动)</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:center">const member functions(保证不更改data members)</td>
<td style="text-align:center">√</td>
<td>√</td>
</tr>
<tr>
<td style="text-align:center">non-const member functions(不保证data members不变)</td>
<td style="text-align:center">×</td>
<td>√</td>
</tr>
</tbody>
</table>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">const</span> String <span class="title">str</span><span class="params">(<span class="string">"hello world"</span>)</span></span>;</span><br><span class="line">str.print();</span><br></pre></td></tr></table></figure>
<p>如果当初设计String::print()时未指明const，那么上行便是经由const object调用non-const member functions，会出错。</p>
<p>标准库中class template std::basic_string&lt;…&gt;有如下两个member functions:</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">charT <span class="keyword">operator</span>[](size_type pos) <span class="keyword">const</span>&#123;...<span class="comment">/*不必考虑COW*/</span>&#125;</span><br><span class="line">reference <span class="keyword">operator</span>[](size_type pos) &#123;...<span class="comment">/*必须考虑COW*/</span>&#125;<span class="comment">//COW:copy on write</span></span><br></pre></td></tr></table></figure>
<p>这是因为string的设计采用了引用计数技术。假设四个string对象可以指向同一个字符串，这样字符串只会存在一份。如果其中一个string对象需要修改字符串，会拷贝出来一份给其，让其去修改，即写时复制。而对于常量string对象，就不会出现修改对象的情况，所以不必考虑写时复制（COW）。</p>
<h1 id="new-delete"><a href="#new-delete" class="headerlink" title="new delete"></a>new delete</h1><p>new先分配内存，在调用构造函数。分配内存调用operator new成员函数，然后调用malloc函数。</p>
<h2 id="重载-operator-new，-operator-delete，-operator-new-，-operator-delete"><a href="#重载-operator-new，-operator-delete，-operator-new-，-operator-delete" class="headerlink" title="重载::operator new，::operator delete，::operator new[]，::operator delete[]"></a>重载::operator new，::operator delete，::operator new[]，::operator delete[]</h2><figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">inline</span> <span class="keyword">void</span> * <span class="keyword">operator</span> <span class="title">new</span><span class="params">(<span class="keyword">size_t</span> size)</span></span>&#123;</span><br><span class="line">	<span class="keyword">return</span> myAlloc(size);</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">inline</span> <span class="keyword">void</span> <span class="keyword">operator</span> <span class="keyword">new</span>[](<span class="keyword">size_t</span>,size)&#123;</span><br><span class="line">    <span class="keyword">return</span> myAlloc(size);</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">inline</span> <span class="keyword">void</span> <span class="keyword">operator</span> <span class="title">delete</span><span class="params">(<span class="keyword">void</span> *ptr)</span></span>&#123;</span><br><span class="line">    myFree(ptr);</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">inline</span> <span class="keyword">void</span> <span class="keyword">operator</span> <span class="keyword">delete</span>[](<span class="keyword">void</span> * ptr)&#123;</span><br><span class="line">    myFree(ptr);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="重载成员函数operator-new-delete"><a href="#重载成员函数operator-new-delete" class="headerlink" title="重载成员函数operator new/delete"></a>重载成员函数operator new/delete</h2><figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Foo</span>&#123;</span></span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">    <span class="function"><span class="keyword">void</span>* <span class="keyword">operator</span> <span class="title">new</span><span class="params">(<span class="keyword">size_t</span> size)</span></span>;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="keyword">operator</span> <span class="title">delete</span><span class="params">(<span class="keyword">void</span>*, <span class="keyword">size_t</span>)</span></span>;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<h2 id="重载成员函数operator-new-delete-1"><a href="#重载成员函数operator-new-delete-1" class="headerlink" title="重载成员函数operator new[]/delete[]"></a>重载成员函数operator new[]/delete[]</h2><figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Foo</span>&#123;</span></span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">    <span class="keyword">void</span>* <span class="keyword">operator</span> <span class="keyword">new</span>[](<span class="keyword">size_t</span> size);</span><br><span class="line">    <span class="keyword">void</span> <span class="keyword">operator</span> <span class="keyword">delete</span>[](<span class="keyword">void</span>*, <span class="keyword">size_t</span>);</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line">Foo * p = <span class="keyword">new</span> Foo[N];</span><br></pre></td></tr></table></figure>
<p>示例： </p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;iostream&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;string&gt;</span></span></span><br><span class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> <span class="built_in">std</span>;</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Foo</span> &#123;</span></span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">	<span class="keyword">int</span> _id;</span><br><span class="line">	<span class="keyword">long</span> _data;</span><br><span class="line">	<span class="built_in">string</span> _str;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">	Foo() : _id(<span class="number">0</span>) &#123; <span class="built_in">cout</span> &lt;&lt; <span class="string">"default ctor.this="</span> &lt;&lt; <span class="keyword">this</span> &lt;&lt; <span class="string">"id="</span> &lt;&lt; _id &lt;&lt; <span class="built_in">endl</span>; &#125;;</span><br><span class="line">	Foo(<span class="keyword">int</span> i) : _id(i) &#123; <span class="built_in">cout</span> &lt;&lt; <span class="string">"ctor.this="</span> &lt;&lt; <span class="keyword">this</span> &lt;&lt; <span class="string">"id="</span> &lt;&lt; _id &lt;&lt; <span class="built_in">endl</span>; &#125;</span><br><span class="line">	<span class="keyword">virtual</span> ~Foo() &#123; <span class="built_in">cout</span> &lt;&lt; <span class="string">"dtor.this="</span> &lt;&lt; <span class="keyword">this</span> &lt;&lt; <span class="string">"id="</span> &lt;&lt; _id &lt;&lt; <span class="built_in">endl</span>; &#125;</span><br><span class="line">	<span class="function"><span class="keyword">static</span> <span class="keyword">void</span> * <span class="keyword">operator</span> <span class="title">new</span><span class="params">(<span class="keyword">size_t</span> size)</span> </span>&#123;</span><br><span class="line">		Foo *p = (Foo *)<span class="built_in">malloc</span>(size);</span><br><span class="line">		<span class="built_in">cout</span> &lt;&lt; <span class="string">"call operator new, size = "</span> &lt;&lt; size  &lt;&lt; <span class="built_in">endl</span>;</span><br><span class="line">		<span class="keyword">return</span> p;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="keyword">operator</span> <span class="title">delete</span><span class="params">(<span class="keyword">void</span> * pdead, <span class="keyword">size_t</span> size)</span> </span>&#123;</span><br><span class="line">		<span class="built_in">cout</span> &lt;&lt; <span class="string">"call operator delete"</span> &lt;&lt; <span class="built_in">endl</span>;</span><br><span class="line">		<span class="built_in">free</span>(pdead);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">static</span> <span class="keyword">void</span> * <span class="keyword">operator</span> <span class="keyword">new</span>[](<span class="keyword">size_t</span> size) &#123;</span><br><span class="line">		Foo *p = (Foo *)<span class="built_in">malloc</span>(size);</span><br><span class="line">		<span class="built_in">cout</span> &lt;&lt; <span class="string">"call operator new[], size="</span> &lt;&lt; size &lt;&lt; <span class="built_in">endl</span>;</span><br><span class="line">		<span class="keyword">return</span> p;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">static</span> <span class="keyword">void</span> <span class="keyword">operator</span> <span class="keyword">delete</span>[](<span class="keyword">void</span> * pdead, <span class="keyword">size_t</span> size) &#123;</span><br><span class="line">		<span class="built_in">cout</span> &lt;&lt; <span class="string">"call operator delete[]"</span> &lt;&lt; <span class="built_in">endl</span>;</span><br><span class="line">		<span class="built_in">free</span>(pdead);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">&#125;;</span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	<span class="built_in">cout</span> &lt;&lt;<span class="string">" sizeof(Foo) = "</span>&lt;&lt; <span class="keyword">sizeof</span>(Foo) &lt;&lt; <span class="built_in">endl</span>;</span><br><span class="line">	Foo * p = <span class="keyword">new</span> Foo();</span><br><span class="line">	Foo *q = <span class="keyword">new</span> Foo[<span class="number">4</span>];</span><br><span class="line">	<span class="keyword">delete</span> p;</span><br><span class="line">	<span class="keyword">delete</span>[]q;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>输出结果：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"> <span class="keyword">sizeof</span>(Foo) = <span class="number">40</span></span><br><span class="line">call <span class="keyword">operator</span> <span class="keyword">new</span>, size = <span class="number">40</span></span><br><span class="line"><span class="keyword">default</span> ctor.<span class="keyword">this</span>=<span class="number">014</span>A5A38id=<span class="number">0</span></span><br><span class="line">call <span class="keyword">operator</span> <span class="keyword">new</span>[], size=<span class="number">164</span></span><br><span class="line"><span class="keyword">default</span> ctor.<span class="keyword">this</span>=<span class="number">014</span>AD92Cid=<span class="number">0</span></span><br><span class="line"><span class="keyword">default</span> ctor.<span class="keyword">this</span>=<span class="number">014</span>AD954id=<span class="number">0</span></span><br><span class="line"><span class="keyword">default</span> ctor.<span class="keyword">this</span>=<span class="number">014</span>AD97Cid=<span class="number">0</span></span><br><span class="line"><span class="keyword">default</span> ctor.<span class="keyword">this</span>=<span class="number">014</span>AD9A4id=<span class="number">0</span></span><br><span class="line">dtor.<span class="keyword">this</span>=<span class="number">014</span>A5A38id=<span class="number">0</span></span><br><span class="line">call <span class="keyword">operator</span> <span class="keyword">delete</span></span><br><span class="line">dtor.<span class="keyword">this</span>=<span class="number">014</span>AD9A4id=<span class="number">0</span></span><br><span class="line">dtor.<span class="keyword">this</span>=<span class="number">014</span>AD97Cid=<span class="number">0</span></span><br><span class="line">dtor.<span class="keyword">this</span>=<span class="number">014</span>AD954id=<span class="number">0</span></span><br><span class="line">dtor.<span class="keyword">this</span>=<span class="number">014</span>AD92Cid=<span class="number">0</span></span><br><span class="line">call <span class="keyword">operator</span> <span class="keyword">delete</span>[]</span><br></pre></td></tr></table></figure>
<p>为什么调用operator new[]打印出来的size是164字节，而不是160字节呢？</p>
<p>这是因为需要一个计数器来记录创建了对象个元素。</p>
<p>如果使用全局的operator new和operator new()，就不会调用类中重载的版本。如下：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	<span class="built_in">cout</span> &lt;&lt;<span class="string">" sizeof(Foo) = "</span>&lt;&lt; <span class="keyword">sizeof</span>(Foo) &lt;&lt; <span class="built_in">endl</span>;</span><br><span class="line">	Foo * p = ::<span class="keyword">new</span> Foo(); <span class="comment">//调用全局::operator new</span></span><br><span class="line">	Foo *q = ::<span class="keyword">new</span> Foo[<span class="number">4</span>];</span><br><span class="line">	::<span class="keyword">delete</span> p;</span><br><span class="line">	::<span class="keyword">delete</span>[]q;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>输出：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">sizeof</span>(Foo) = <span class="number">40</span></span><br><span class="line"><span class="keyword">default</span> ctor.<span class="keyword">this</span>=<span class="number">011E4</span>D48id=<span class="number">0</span></span><br><span class="line"><span class="keyword">default</span> ctor.<span class="keyword">this</span>=<span class="number">011E98</span>FCid=<span class="number">0</span></span><br><span class="line"><span class="keyword">default</span> ctor.<span class="keyword">this</span>=<span class="number">011E9924</span>id=<span class="number">0</span></span><br><span class="line"><span class="keyword">default</span> ctor.<span class="keyword">this</span>=<span class="number">011E994</span>Cid=<span class="number">0</span></span><br><span class="line"><span class="keyword">default</span> ctor.<span class="keyword">this</span>=<span class="number">011E9974</span>id=<span class="number">0</span></span><br><span class="line">dtor.<span class="keyword">this</span>=<span class="number">011E4</span>D48id=<span class="number">0</span></span><br><span class="line">dtor.<span class="keyword">this</span>=<span class="number">011E9974</span>id=<span class="number">0</span></span><br><span class="line">dtor.<span class="keyword">this</span>=<span class="number">011E994</span>Cid=<span class="number">0</span></span><br><span class="line">dtor.<span class="keyword">this</span>=<span class="number">011E9924</span>id=<span class="number">0</span></span><br><span class="line">dtor.<span class="keyword">this</span>=<span class="number">011E98</span>FCid=<span class="number">0</span></span><br></pre></td></tr></table></figure>
<h2 id="重载new-和delete"><a href="#重载new-和delete" class="headerlink" title="重载new()和delete()"></a>重载new()和delete()</h2><p>可以重载class member operator  new()，写出多个版本，前提是每一个版本的声明都必须有独特的参数，其中第一个参数都必须是size_t，其余参数以new所指定的placement 参数为初值。出现new()小括号内的便是居中对齐placement参数：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Foo *pf = <span class="keyword">new</span>(<span class="number">300</span>, <span class="string">'c'</span>)Foo;</span><br></pre></td></tr></table></figure>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> * <span class="keyword">operator</span> <span class="title">new</span><span class="params">(<span class="keyword">size_t</span> size, <span class="keyword">void</span> * start)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">return</span> start;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">void</span> * <span class="keyword">operator</span> <span class="title">new</span><span class="params">(<span class="keyword">size_t</span> size, <span class="keyword">long</span> extra)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">return</span> <span class="built_in">malloc</span>(size + extra);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">void</span> * <span class="keyword">operator</span> <span class="title">new</span><span class="params">(<span class="keyword">size_t</span> size, <span class="keyword">long</span> extra, <span class="keyword">char</span> init)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">return</span> <span class="built_in">malloc</span>(size + extra + <span class="keyword">sizeof</span>(init));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>也可以重载class member operator delete()，写出多个版本。但它们绝不会被delete调用。只会当new所调用的构造函数抛出异常，才会调用这些重载的operator delete()。它只可能这样被调用，主要用来归还未能完全创建成功的对象所占用的内存。</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;iostream&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;string&gt;</span></span></span><br><span class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> <span class="built_in">std</span>;</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Bad</span>&#123;</span>&#125;;</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Foo</span> &#123;</span></span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">	<span class="keyword">int</span> _id;</span><br><span class="line">	<span class="keyword">long</span> _data;</span><br><span class="line">	<span class="built_in">string</span> _str;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">	Foo() : _id(<span class="number">0</span>) &#123; <span class="built_in">cout</span> &lt;&lt; <span class="string">"default ctor.this="</span> &lt;&lt; <span class="keyword">this</span> &lt;&lt; <span class="string">"id="</span> &lt;&lt; _id &lt;&lt; <span class="built_in">endl</span>; &#125;;</span><br><span class="line">	Foo(<span class="keyword">int</span> i) : _id(i) &#123; <span class="built_in">cout</span> &lt;&lt; <span class="string">"ctor.this="</span> &lt;&lt; <span class="keyword">this</span> &lt;&lt; <span class="string">"id="</span> &lt;&lt; _id &lt;&lt; <span class="built_in">endl</span>;  </span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">virtual</span> ~Foo() &#123; <span class="built_in">cout</span> &lt;&lt; <span class="string">"dtor.this="</span> &lt;&lt; <span class="keyword">this</span> &lt;&lt; <span class="string">"id="</span> &lt;&lt; _id &lt;&lt; <span class="built_in">endl</span>; &#125;</span><br><span class="line">	<span class="function"><span class="keyword">static</span> <span class="keyword">void</span> * <span class="keyword">operator</span> <span class="title">new</span><span class="params">(<span class="keyword">size_t</span> size)</span> </span>&#123;</span><br><span class="line">		Foo *p = (Foo *)<span class="built_in">malloc</span>(size);</span><br><span class="line">		<span class="built_in">cout</span> &lt;&lt; <span class="string">"call operator new, size = "</span> &lt;&lt; size  &lt;&lt; <span class="built_in">endl</span>;</span><br><span class="line">		<span class="keyword">return</span> p;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="keyword">operator</span> <span class="title">delete</span><span class="params">(<span class="keyword">void</span> * pdead, <span class="keyword">size_t</span> size)</span> </span>&#123;</span><br><span class="line">		<span class="built_in">cout</span> &lt;&lt; <span class="string">"call operator delete"</span> &lt;&lt; <span class="built_in">endl</span>;</span><br><span class="line">		<span class="built_in">free</span>(pdead);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">static</span> <span class="keyword">void</span> * <span class="keyword">operator</span> <span class="keyword">new</span>[](<span class="keyword">size_t</span> size) &#123;</span><br><span class="line">		Foo *p = (Foo *)<span class="built_in">malloc</span>(size);</span><br><span class="line">		<span class="built_in">cout</span> &lt;&lt; <span class="string">"call operator new[], size="</span> &lt;&lt; size &lt;&lt; <span class="built_in">endl</span>;</span><br><span class="line">		<span class="keyword">return</span> p;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">static</span> <span class="keyword">void</span> <span class="keyword">operator</span> <span class="keyword">delete</span>[](<span class="keyword">void</span> * pdead, <span class="keyword">size_t</span> size) &#123;</span><br><span class="line">		<span class="built_in">cout</span> &lt;&lt; <span class="string">"call operator delete[]"</span> &lt;&lt; <span class="built_in">endl</span>;</span><br><span class="line">		<span class="built_in">free</span>(pdead);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">void</span> * <span class="keyword">operator</span> <span class="title">new</span><span class="params">(<span class="keyword">size_t</span> size, <span class="keyword">void</span> * start)</span> </span>&#123;</span><br><span class="line">		<span class="built_in">cout</span> &lt;&lt; <span class="string">"operator new(sizt_t, void*)"</span> &lt;&lt; <span class="built_in">endl</span>;</span><br><span class="line">		<span class="keyword">return</span> start;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">void</span> * <span class="keyword">operator</span> <span class="title">new</span><span class="params">(<span class="keyword">size_t</span> size, <span class="keyword">long</span> extra)</span> </span>&#123;</span><br><span class="line">		<span class="built_in">cout</span> &lt;&lt; <span class="string">"operator new(size_t, long)"</span> &lt;&lt; <span class="built_in">endl</span>;</span><br><span class="line">		<span class="keyword">return</span> <span class="built_in">malloc</span>(size + extra);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">void</span> * <span class="keyword">operator</span> <span class="title">new</span><span class="params">(<span class="keyword">size_t</span> size, <span class="keyword">long</span> extra, <span class="keyword">char</span> init)</span> </span>&#123;</span><br><span class="line">		<span class="built_in">cout</span> &lt;&lt; <span class="string">"operator new(size_t, long, char)"</span> &lt;&lt; <span class="built_in">endl</span>;</span><br><span class="line">		<span class="keyword">return</span> <span class="built_in">malloc</span>(size + extra + <span class="keyword">sizeof</span>(init));</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">void</span> <span class="keyword">operator</span> <span class="title">delete</span><span class="params">(<span class="keyword">void</span> * , <span class="keyword">void</span> *)</span> </span>&#123;</span><br><span class="line">		<span class="built_in">cout</span> &lt;&lt; <span class="string">"operator delete(void*, void)"</span> &lt;&lt; <span class="built_in">endl</span>;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">void</span> <span class="keyword">operator</span> <span class="title">delete</span><span class="params">(<span class="keyword">void</span> * ,<span class="keyword">long</span>)</span> </span>&#123;</span><br><span class="line">		<span class="built_in">cout</span> &lt;&lt; <span class="string">"operator delete(void * ,long)"</span> &lt;&lt; <span class="built_in">endl</span>;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">void</span> <span class="keyword">operator</span> <span class="title">delete</span><span class="params">(<span class="keyword">void</span> *, <span class="keyword">long</span>, <span class="keyword">char</span>)</span> </span>&#123;</span><br><span class="line">		<span class="built_in">cout</span> &lt;&lt; <span class="string">"operator delete(void *, long, char)"</span> &lt;&lt; <span class="built_in">endl</span>;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">&#125;;</span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	<span class="built_in">cout</span> &lt;&lt;<span class="string">" sizeof(Foo) = "</span>&lt;&lt; <span class="keyword">sizeof</span>(Foo) &lt;&lt; <span class="built_in">endl</span>;</span><br><span class="line">	Foo * p1 = <span class="keyword">new</span> Foo;</span><br><span class="line">	Foo * p2 = <span class="keyword">new</span>(<span class="number">100</span>,<span class="string">'c'</span>)Foo;</span><br><span class="line">	Foo * p3 = <span class="keyword">new</span>(<span class="number">100</span>)Foo(<span class="number">1</span>);</span><br><span class="line">	Foo * p = ::<span class="keyword">new</span> Foo();</span><br><span class="line">	Foo *q = ::<span class="keyword">new</span> Foo[<span class="number">4</span>];</span><br><span class="line">	::<span class="keyword">delete</span> p;</span><br><span class="line">	::<span class="keyword">delete</span>[]q;</span><br><span class="line">&#125;</span><br><span class="line">输出：</span><br><span class="line"> <span class="keyword">sizeof</span>(Foo) = <span class="number">40</span></span><br><span class="line">call <span class="keyword">operator</span> <span class="keyword">new</span>, size = <span class="number">40</span></span><br><span class="line"><span class="keyword">default</span> ctor.<span class="keyword">this</span>=<span class="number">00B</span>55B18id=<span class="number">0</span></span><br><span class="line"><span class="keyword">operator</span> <span class="keyword">new</span>(<span class="keyword">size_t</span>, <span class="keyword">long</span>, <span class="keyword">char</span>)</span><br><span class="line"><span class="keyword">default</span> ctor.<span class="keyword">this</span>=<span class="number">00B</span>61838id=<span class="number">0</span></span><br><span class="line"><span class="keyword">operator</span> <span class="keyword">new</span>(<span class="keyword">size_t</span>, <span class="keyword">long</span>)</span><br><span class="line">ctor.<span class="keyword">this</span>=<span class="number">00B</span>63BC0id=<span class="number">1</span></span><br><span class="line"><span class="keyword">default</span> ctor.<span class="keyword">this</span>=<span class="number">00B</span>54E28id=<span class="number">0</span></span><br><span class="line"><span class="keyword">default</span> ctor.<span class="keyword">this</span>=<span class="number">00B</span>63C7Cid=<span class="number">0</span></span><br><span class="line"><span class="keyword">default</span> ctor.<span class="keyword">this</span>=<span class="number">00B</span>63CA4id=<span class="number">0</span></span><br><span class="line"><span class="keyword">default</span> ctor.<span class="keyword">this</span>=<span class="number">00B</span>63CCCid=<span class="number">0</span></span><br><span class="line"><span class="keyword">default</span> ctor.<span class="keyword">this</span>=<span class="number">00B</span>63CF4id=<span class="number">0</span></span><br><span class="line">dtor.<span class="keyword">this</span>=<span class="number">00B</span>54E28id=<span class="number">0</span></span><br><span class="line">dtor.<span class="keyword">this</span>=<span class="number">00B</span>63CF4id=<span class="number">0</span></span><br><span class="line">dtor.<span class="keyword">this</span>=<span class="number">00B</span>63CCCid=<span class="number">0</span></span><br><span class="line">dtor.<span class="keyword">this</span>=<span class="number">00B</span>63CA4id=<span class="number">0</span></span><br><span class="line">dtor.<span class="keyword">this</span>=<span class="number">00B</span>63C7Cid=<span class="number">0</span></span><br></pre></td></tr></table></figure>
<h2 id="basic-string使用new-extra-扩充申请量"><a href="#basic-string使用new-extra-扩充申请量" class="headerlink" title="basic_string使用new(extra)扩充申请量"></a>basic_string使用new(extra)扩充申请量</h2><p><img src="https://raw.githubusercontent.com/zxpgo/images/master/img/20190901203455.png" alt=""></p>
<p>Rep是一个引用计数。</p>

      
    </div>
    
    
    

    
      <div>
        <div id="wechat_subscriber" style="display: block; padding: 10px 0; margin: 20px auto; width: 100%; text-align: center">
    <img id="wechat_subscriber_qcode" src="/images/wechat-qcode.jpg" alt="zxp wechat" style="width: 200px; max-width: 100%;"/>
    <div>欢迎关注微信公众号！</div>
</div>

      </div>
    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div></div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/WeChatpay.jpg" alt="zxp 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/Alipay.jpg" alt="zxp 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    zxp
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://zxpgo.github.io/2019/08/06/C++对象模型/" title="C++对象模型">https://zxpgo.github.io/2019/08/06/C++对象模型/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tag/C/" rel="tag"># C++</a>
          
        </div>
      

      
      
        <div class="post-widgets">
        

        

        
          
          <div id="needsharebutton-postbottom">
            <span class="btn">
              <i class="fa fa-share-alt" aria-hidden="true"></i>
            </span>
          </div>
        
        </div>
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/08/04/k8s/" rel="next" title="k8s基本概念">
                <i class="fa fa-chevron-left"></i> k8s基本概念
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/08/06/C++面向对象高级编程/" rel="prev" title="C++面向对象高级编程">
                C++面向对象高级编程 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC8zODgxNC8xNTM0Mg=="></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/avatar.gif"
                alt="zxp" />
            
              <p class="site-author-name" itemprop="name">zxp</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">176</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">16</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">48</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://blog.csdn.net/qq_25774883" target="_blank" title="CSDN">
                      
                        <i class="fa fa-fw fa-globe"></i>CSDN</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/zxpgo/zxpgo" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-globe"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://www.linkedin.com/feed/" target="_blank" title="LinkedIn">
                      
                        <i class="fa fa-fw fa-globe"></i>LinkedIn</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="1165772354@qq.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-inline">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                友情链接
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="http://theme-next.iissnan.com" title="Next主题" target="_blank">Next主题</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://blog.rexking6.top" title="青爷博客" target="_blank">青爷博客</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://me.csdn.net/download/qq_25774883" title="CSDN下载" target="_blank">CSDN下载</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.livere.com/" title="来必力" target="_blank">来必力</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://tongji.baidu.com/web/welcome/login" title="百度统计" target="_blank">百度统计</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://leancloud.cn/" title="LeanCloud" target="_blank">LeanCloud</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://ibruce.info/2015/04/04/busuanzi/" title="不蒜子" target="_blank">不蒜子</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://leetcode-cn.com/" title="LeetCode" target="_blank">LeetCode</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#类型转换"><span class="nav-number">1.</span> <span class="nav-text">类型转换</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#转换函数"><span class="nav-number">1.1.</span> <span class="nav-text">转换函数</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#non-explicit-one-argument-ctor"><span class="nav-number">1.2.</span> <span class="nav-text">non-explicit-one-argument ctor</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#explicit-one-argument-ctor"><span class="nav-number">1.3.</span> <span class="nav-text">explicit-one-argument ctor</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#pointer-liker-classes"><span class="nav-number">2.</span> <span class="nav-text">pointer-liker classes</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#智能指针"><span class="nav-number">2.1.</span> <span class="nav-text">智能指针</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#迭代器"><span class="nav-number">2.2.</span> <span class="nav-text">迭代器</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#function-like-classes仿函数"><span class="nav-number">3.</span> <span class="nav-text">function-like classes仿函数</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#模板"><span class="nav-number">4.</span> <span class="nav-text">模板</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#类模板"><span class="nav-number">4.1.</span> <span class="nav-text">类模板</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#函数模板"><span class="nav-number">4.2.</span> <span class="nav-text">函数模板</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#成员模板"><span class="nav-number">4.3.</span> <span class="nav-text">成员模板</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#模板特化"><span class="nav-number">4.4.</span> <span class="nav-text">模板特化</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#模板偏特化"><span class="nav-number">4.5.</span> <span class="nav-text">模板偏特化</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#模板模板参数"><span class="nav-number">4.6.</span> <span class="nav-text">模板模板参数</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#模板参数可变"><span class="nav-number">4.7.</span> <span class="nav-text">模板参数可变</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#引用"><span class="nav-number">5.</span> <span class="nav-text">引用</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#对象模型"><span class="nav-number">6.</span> <span class="nav-text">对象模型</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#虚指针和虚表"><span class="nav-number">6.1.</span> <span class="nav-text">虚指针和虚表</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#this"><span class="nav-number">7.</span> <span class="nav-text">this</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#const"><span class="nav-number">8.</span> <span class="nav-text">const</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#new-delete"><span class="nav-number">9.</span> <span class="nav-text">new delete</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#重载-operator-new，-operator-delete，-operator-new-，-operator-delete"><span class="nav-number">9.1.</span> <span class="nav-text">重载::operator new，::operator delete，::operator new[]，::operator delete[]</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#重载成员函数operator-new-delete"><span class="nav-number">9.2.</span> <span class="nav-text">重载成员函数operator new/delete</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#重载成员函数operator-new-delete-1"><span class="nav-number">9.3.</span> <span class="nav-text">重载成员函数operator new[]/delete[]</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#重载new-和delete"><span class="nav-number">9.4.</span> <span class="nav-text">重载new()和delete()</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#basic-string使用new-extra-扩充申请量"><span class="nav-number">9.5.</span> <span class="nav-text">basic_string使用new(extra)扩充申请量</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div>
<script async src="https//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<i class="fa fa-user-md"></i><span id="busuanzi_container_site_pv" style='display:none'>
    本站总访问量 <span id="busuanzi_value_site_pv"></span> 
    <span class="post-meta-divider">|</span>
</span>
<span id="busuanzi_container_site_uv" style='display:none'>
    访问人数 <span id="busuanzi_value_site_uv"></span>
</span>
</div>


<script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

<div class="copyright">&copy; 2018-8 &mdash; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-"></i> Power by 
  </span>
  <span class="author" itemprop="copyrightHolder">zxp</span>
  
  
</div>









        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    
      <div id="needsharebutton-float">
        <span class="btn">
          <i class="fa fa-share-alt" aria-hidden="true"></i>
        </span>
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  




  
  <div id="lv-container" data-uid="MTAyMC8zODgxNC8xNTM0Mg==">
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
	</div>
  











  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("2AyV3DKioBSdoryrFLRohzjB-gzGzoHsz", "XynedcHyJCVCrTfbD4yYnodo");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
  
  
  <link rel="stylesheet" href="/lib/needsharebutton/needsharebutton.css">

  
  
  <script src="/lib/needsharebutton/needsharebutton.js"></script>

  <script>
    
      pbOptions = {};
      
          pbOptions.iconStyle = "default";
      
          pbOptions.boxForm = "vertical";
      
          pbOptions.position = "top";
      
          pbOptions.networks = "Weibo,Wechat,Douban,QQZone,Twitter,Facebook";
      
      new needShareButton('#needsharebutton-postbottom', pbOptions);
    
    
      flOptions = {};
      
          flOptions.iconStyle = "box";
      
          flOptions.boxForm = "horizontal";
      
          flOptions.position = "middleRight";
      
          flOptions.networks = "Weibo,Wechat,Douban,QQZone,Twitter,Facebook";
      
      new needShareButton('#needsharebutton-float', flOptions);
    
  </script>

  

  
  
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script type="text/javascript" src="//cdn.bootcss.com/mathjax/2.7.1/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
  


  
  <script type="text/javascript" src="/js/src/js.cookie.js?v=5.1.4"></script>
  <script type="text/javascript" src="/js/src/scroll-cookie.js?v=5.1.4"></script>


  
  <script type="text/javascript" src="/js/src/exturl.js?v=5.1.4"></script>


  
  
  	 <!-- custom analytics part create by xiamo -->
<script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.1.js"></script>
<script>AV.initialize("2AyV3DKioBSdoryrFLRohzjB-gzGzoHsz", "XynedcHyJCVCrTfbD4yYnodo");</script>
<script>
function showTime(Counter) {
	var query = new AV.Query(Counter);
	$(".leancloud_visitors").each(function() {
		var url = $(this).attr("id").trim();
		query.equalTo("url", url);
		query.find({
			success: function(results) {
				if (results.length == 0) {
					var content = $(document.getElementById(url)).text() + ' 0';
					$(document.getElementById(url)).text(content);
					return;
				}
				for (var i = 0; i < results.length; i++) {
					var object = results[i];
					var content = $(document.getElementById(url)).text() + ' ' + object.get('time');
					$(document.getElementById(url)).text(content);
				}
			}
		});

	});
}

</script>
  
</body>
</html>
